<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

class Admin_Settings extends Admin_Controller {
	public function __construct()
	{
		parent::Admin_Controller();
		$this->config->load('cirpho');
		$this->load->helper('form');
		$this->lang->load('cirpho');
		$this->lang->load('settings');
		$this->load->model('cip_settings_m');
		$this->load->model('cip_servers_m');
		$this->template
			->append_metadata( css('cirpho.css', 'cirpho') )
			->append_metadata(js('cirpho.js', 'cirpho'))
			->set_partial('shortcuts', 'admin/partials/shortcuts');
		// Set the validation rules
		$this->load->library('form_validation');
		$this->validation_rules1 = array(
			array(
				'field' => 'minimum_matching_rate',
				'label' => lang('cirpho_setting_minimum_matching_rate'),
				'rules' => 'trim|required|max_length[3]'
			),
			array(
				'field' => 'decision_matching_rate',
				'label' => lang('cirpho_setting_decision_matching_rate'),
				'rules' => 'trim|required|max_length[3]'
			),
		);
		$this->validation_rules2 = array(	
			array(
				'field' => 'max_width',
				'label' => lang('cirpho_setting_max_width'),
				'rules' => 'trim|required|max_length[20]'
			)
			/*,
			array(
				'field' => 'max_height',
				'label' => lang('cirpho_setting_max_height'),
				'rules' => 'trim|required|max_length[20]|integer'
			)
			*/
		);
		$this->_path = FCPATH . $this->config->item('files_folder');
		$this->_command_path = $this->config->item('command_folder');
		$this->_rebuild_command_folder = $this->config->item('rebuild_command_folder');
	}
	public function index()
	{
		if(isset($_POST['server']) && $_POST['server'] != "0"){
			$selectedServer = $this->cip_servers_m->get_by('id',$_POST['server']);
		}else{
			$selectedServer = null;
		}
		
		
		$minimum_matching_rate = $this->cip_settings_m->get('minimum_matching_rate');
		$decision_matching_rate = $this->cip_settings_m->get('decision_matching_rate');
		$max_width = $this->cip_settings_m->get('max_width');
		$max_height = $this->cip_settings_m->get('max_height');
		
		if($_POST['rebuild']){
			$this->form_validation->set_rules($this->validation_rules2);
		}else if($_POST['btnAction']){
			$this->form_validation->set_rules($this->validation_rules1);	
		}
		
		// Validate the data
		if ($this->form_validation->run())
		{
			if($_POST['rebuild']){
								
				$this->cip_settings_m->update($max_width->id, $_POST['max_width']);

				$servers = $this->cip_servers_m->get_all();
				$isSuccess = true;
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSetMaxWidth = array(
								'name'	=> 'max_width',
								'value' => $_POST['max_width']
						);
						
						$this->client_db->where('id', $max_width->id);
						$this->client_db->update('default_cip_settings', $dataSetMaxWidth);
						
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							$oldDataSetMaxWidth = array(
								'name'	=> 'max_width',
								'value' => $max_width->value
							);
							$this->cip_settings_m->update($max_width->id, $max_width->value);
						
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->where('id', $max_width->id);
								$this->client_db->update('default_cip_settings', $oldDataSetMaxWidth);
								
								
							}
							break;
						}
					}
				}
				
				//echo "sh ".$this->_rebuild_command_folder."rebuild.sh ".substr($this->_path, 0, strlen($this->_path) -1 )." ".$_POST['max_width'];				
				system("sh ".$this->_rebuild_command_folder."rebuild.sh ".substr($this->_path, 0, strlen($this->_path) -1 )." ".$_POST['max_width']);
				//die();
				
				if($isSuccess){
					$this->session->set_flashdata('success', lang('cirpho_setting_rebuild_success'));
				}else{
					$this->session->set_flashdata('error', lang('cirpho_setting_rebuild_error'));
				}
			}else{
				$this->cip_settings_m->update($minimum_matching_rate->id, $_POST['minimum_matching_rate']);
				$this->cip_settings_m->update($decision_matching_rate->id, $_POST['decision_matching_rate']);
				
				$servers = $this->cip_servers_m->get_all();
				$isSuccess = true;
				if($servers && count($servers)){
					foreach ($servers as $server){
						
						$config['hostname'] = $server->domain_name;
						$config['username'] = $server->database_user;
						$config['password'] = $server->database_password;
						$config['database'] = $server->database_name;
						$config['dbdriver'] = "mysql";
						$config['dbprefix'] = "";
						$config['pconnect'] = FALSE;
						$config['db_debug'] = FALSE;
						$config['cache_on'] = FALSE;
						$config['cachedir'] = "";
						$config['char_set'] = "utf8";
						$config['dbcollat'] = "utf8_general_ci";
						$config['port'] 	= 3306;
						
						$this->client_db = $this->load->database($config, TRUE);
						
						$dataSetMinimum = array(
								'name'	=> 'minimum_matching_rate',
								'value' => $_POST['minimum_matching_rate']
						);
						
						$dataSetDecision = array(
								'name'	=> 'decision_matching_rate',
								'value' => $_POST['decision_matching_rate']
						);
						$this->client_db->where('id', $minimum_matching_rate->id);
						$this->client_db->update('default_cip_settings', $dataSetMinimum);
					    
						$this->client_db->where('id', $decision_matching_rate->id);
						$this->client_db->update('default_cip_settings', $dataSetDecision);
						
					    $e = $this->client_db->_error_message();
					    $aff = $this->client_db->affected_rows();
						
						if($aff < 1) {
							$isSuccess = false;
							//echo "Error";
							//echo $e;
							
							$oldDataSetMinimum = array(
								'name'	=> 'minimum_matching_rate',
								'value' => $minimum_matching_rate->value
							);
							$oldDataSetDecision = array(
								'name'	=> 'decision_matching_rate',
								'value' => $decision_matching_rate->value
							);

							$this->cip_settings_m->update($minimum_matching_rate->id, $minimum_matching_rate->value);
							$this->cip_settings_m->update($decision_matching_rate->id, $decision_matching_rate->value);
						
							foreach ($servers as $server){
								$config['hostname'] = $server->domain_name;
								$config['username'] = $server->database_user;
								$config['password'] = $server->database_password;
								$config['database'] = $server->database_name;
								$config['dbdriver'] = "mysql";
								$config['dbprefix'] = "";
								$config['pconnect'] = FALSE;
								$config['db_debug'] = FALSE;
								$config['cache_on'] = FALSE;
								$config['cachedir'] = "";
								$config['char_set'] = "utf8";
								$config['dbcollat'] = "utf8_general_ci";
								$config['port'] 	= 3306;
								
								$this->client_db = $this->load->database($config, TRUE);

								$this->client_db->where('id', $minimum_matching_rate->id);
								$this->client_db->update('default_cip_settings', $oldDataSetMinimum);
					    
								$this->client_db->where('id', $decision_matching_rate->id);
								$this->client_db->update('default_cip_settings', $oldDataSetDecision);
								
								
							}
							break;
						}
					}
				}
				
				if($isSuccess){
					$this->session->set_flashdata('success', lang('cirpho_setting_update_success'));
				}else{
					$this->session->set_flashdata('error', lang('cirpho_setting_update_error'));
				}
				
			}
				
			redirect('admin/cirpho/settings');
		}
	
		$this->pyrocache->delete_all('modules_m');
		$servers = $this->cip_servers_m->order_by('name', 'ASC')->get_all();
		$this->template
			->title($this->module_details['name'], lang('cirpho_setting_title'))
			->set('minimum_matching_rate', $minimum_matching_rate)
			->set('decision_matching_rate', $decision_matching_rate)
			->set('max_width', $max_width)
			->set('max_height', $max_height)
			->set('servers', $servers)
			->set('selectedServer', $selectedServer)
			->build('admin/settings/form', $this->data);
	}
	
	/**
	 * Callback method that checks the title of the category
	 * @access public
	 * @param string title The title to check
	 * @return bool
	 */
	public function _check_title($name = '')
	{
		if ($this->cip_owners_m->check_title($name))
		{
			$this->form_validation->set_message('_check_title', sprintf($this->lang->line('cirpho_owner_already_exist_error'), $name));
			return FALSE;
		}

		return TRUE;
	}
}